import {
  Avatar,
  Card,
  Col,
  List,
  Skeleton,
  Button,
  Divider,
  Row,
  Statistic,
  Modal,
  Form,
  InputNumber,
  Input,
  message,
  Table,
  Descriptions,
  PageHeader,
  Tag
} from 'antd';
import React, {Component, Suspense} from 'react';

import {Dispatch} from 'redux';
import Link from 'umi/link';
import {PageHeaderWrapper,} from '@ant-design/pro-layout';
import {connect} from 'dva';
import moment from 'moment';
import {ModalState} from './model';
import EditableLinkGroup from './components/EditableLinkGroup';
import styles from './style.less';
import {ActivitiesType, CurrentUser, NoticeType, RadarDataType} from './data.d';
import ExportVolumeChart from './components/ExportVolumeChart';
import ForeignExchangeAmountChart from './components/ForeignExchangeAmountChart';
import OrderCountChart from './components/OrderCountChart';
import axios from '@/components/Engineering/axios';
import QuickTool from '@/components/Engineering/QuickTool';
import moment = require("moment");

const FormItem = Form.Item
const links = [
  {
    title: '我的消息',
    href: '/manage/person/message',
  },
  {
    title: '密码修改',
    href: '/manage/person/password',
  },
  {
    title: '账号信息修改',
    href: '/manage/person/baseinfo',
  },
  {
    title: '我的企业',
    href: '/manage/enterprise/my',
  },
  {
    title: '企业成员管理',
    href: '/manage/enterprise/member',
  },
  {
    title: '对账明细查询',
    href: '/manage/enterprise/accountRecord',
  },
  {
    title: '代理服务订单',
    href: '/manage/order/agent',
  },
  {
    title: '生成报关资料',
    href: '/manage/service/customsInfoGenerate',
  },
  {
    title: '国外买家查询',
    href: '/manage/service/foreignTraderQuery',
  },
];

interface WorkplaceProps {
  currentUser: CurrentUser;
  projectNotice: NoticeType[];
  activities: ActivitiesType[];
  radarData: RadarDataType[];
  dispatch: Dispatch<any>;
  currentUserLoading: boolean;
  projectLoading: boolean;
  activitiesLoading: boolean;
}

const PageHeaderContent: React.FC<{ currentUser: CurrentUser, callback: any, amtdetailData: any }> = ({currentUser, callback, amtdetailData}) => {
  const loading = currentUser && Object.keys(currentUser).length;
  if (!loading) {
    return <Skeleton avatar paragraph={{rows: 1}} active/>;
  }
  return (
    <div className={styles.pageHeaderContent}>
      <div className={styles.avatar}>
        <Avatar size="large" src={currentUser.avatar}/>
      </div>
      <div className={styles.content}>
        <div className={styles.contentTitle}>
          您好，
          {currentUser.name}
          ，祝你开心每一天！
        </div>
        <div>
          {currentUser.title}
          <Divider type="vertical"/>
          {currentUser.group}
        </div>
        <div style={{marginTop: 15}}>
          <Button type="primary" size="small" style={{marginRight: 15}}
                  onClick={() => callback({cashVisible: true})}>提现</Button>
          <Button type="dashed" size="small" onClick={() => {
            callback({cashRecordVisible: true})
          }}>提现记录查询</Button>
        </div>


        <Descriptions size="small" column={2} style={{marginTop:10}} >
          <Descriptions.Item label="历史结算余额"><a>{amtdetailData.historyAmt}</a></Descriptions.Item>
          <Descriptions.Item label="结汇款"><a>{amtdetailData.forexAmt}</a></Descriptions.Item>
          <Descriptions.Item label="退税融资款"><a>{amtdetailData.refundFinanceAmt}</a></Descriptions.Item>
          <Descriptions.Item label="本地费用"><a>{amtdetailData.chargeAmt}</a></Descriptions.Item>
          <Descriptions.Item label="保证金"><a>{amtdetailData.depositAmt}</a></Descriptions.Item>
          <Descriptions.Item label="可释放保证金"><a>{ amtdetailData.releaseDepositAmt}</a></Descriptions.Item>


        </Descriptions>

      </div>
    </div>
  );
};

const ExtraContent: React.FC<{}> = ({amtdetailData}) => {

  let totalAmout = amtdetailData.historyAmt + amtdetailData.forexAmt + amtdetailData.refundFinanceAmt + amtdetailData.depositAmt;

  let canUseAmout = totalAmout - amtdetailData.chargeAmt - amtdetailData.depositAmt;

  return (
    <div className={styles.extraContent}>
      <div className={styles.statItem}>
        <Statistic title="可用余额" value={canUseAmout ? canUseAmout : 0} precision={2}/>
      </div>
      <div className={styles.statItem}>
        <Statistic title="总余额" value={totalAmout ? totalAmout : 0} precision={2}/>
      </div>
      {/* <div className={styles.statItem}>
        <Statistic title="排名" value={1034} suffix="/ 5123"/>
      </div> */}
    </div>
  );
};

@connect(
  ({
     dashboardWorkplace: {currentUser, amtdetailData},
     loading,
   }: {
    dashboardWorkplace: ModalState;
    loading: { effects: any };
  }) => ({
    currentUser,
    amtdetailData,
    fetchAmtdetailDataLoading: loading.effects['dashboardWorkplace/fetchAmtdetailData'],
    fetchQueryYearRecamountDataLoading: loading.effects['dashboardWorkplace/fetchQueryYearRecamountData'],
    fetchAmtdetailDataLoading: loading.effects['dashboardWorkplace/fetchAmtdetailData'],
  }),
)
class Workplace extends Component<WorkplaceProps> {

  state = {
    cashVisible: false,
    cashRecordVisible: false,
    CashRecordList: {},
  }

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'dashboardWorkplace/init',
    });
    this.getCashRecord()
  }

  componentWillUnmount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'dashboardWorkplace/clear',
    });
  }


  getCashRecord() {
    axios.ajax({url: `${MC_PATH}/api/presentrecords`}).then(res => {
      res.content && this.setState({
        CashRecordList: res.content.list
      })
    })
  }

  renderActivities = (item: ActivitiesType) => {
    const events = item.template.split(/@\{([^{}]*)\}/gi).map(key => {
      if (item[key]) {
        return (
          <a href={item[key].link} key={item[key].name}>
            {item[key].name}
          </a>
        );
      }
      return key;
    });
    return (
      <List.Item key={item.id}>
        <List.Item.Meta
          avatar={<Avatar src={item.user.avatar}/>}
          title={
            <span>
              <a className={styles.username}>{item.user.name}</a>
              &nbsp;
              <span className={styles.event}>{events}</span>
            </span>
          }
          description={
            <span className={styles.datetime} title={item.updatedAt}>
              {moment(item.updatedAt).fromNow()}
            </span>
          }
        />
      </List.Item>
    );
  };


  columns = [
    {title: '申请时间', dataIndex: 'createtime', key: 'createtime'},
    {title: '结算金额', dataIndex: 'amt', key: 'amt'},
    // {
    //   title: '当前状态', dataIndex: 'status', key: 'status', render: (text) => {
    //     return {'1': '待处理', '2': '已结算', '3': '结算失败'}[text] || '状态未知'
    //   }
    // },
    {
      title: '结算金额', dataIndex: 'status', key: 'status', render: QuickTool.tag({
        '1': {text: '待处理', color: "red"},
        '2': {text: '已结算', color: "green"},
        '3': {text: '结算失败', color: "#2db7f5"},
      })
    },

  ];

  render() {
    const {
      currentUser,
      fetchAmtdetailDataLoading,
      projectLoading,
      amtdetailData,
      dispatch,
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 24},
        md: {span: 4},
        lg: {span: 7},
        xl: {span: 6},
        xxl: {span: 6},

      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 24},
        md: {span: 17},
        lg: {span: 17},
        xl: {span: 18},
        xxl: {span: 18},
      },
    };


    const {
      getFieldDecorator,
    } = this.props.form;

    return (
      <PageHeaderWrapper
        content={<PageHeaderContent currentUser={currentUser} amtdetailData={amtdetailData[0]?amtdetailData[0]:{}} callback={(params: any) => {
          this.setState({...params})
        }}/>}
        extraContent={<ExtraContent amtdetailData={amtdetailData[0] ? amtdetailData[0] : {forexAmt: 0}}/>}
      >


        <Row gutter={24}>
          <Col xl={16} lg={24} md={24} sm={24} xs={24}>
            <Card
              headStyle={{border: 0}}
              style={{marginBottom: 24}}
              title="出口金额统计（已通关订单数据）"
              bordered={false}
              extra={
                <span>
                  <Button type="link" onClick={
                    () => {
                      dispatch({
                        type: 'dashboardWorkplace/fetchQueryYearExportvolumeData',
                        payload: {
                          date: moment().subtract(2, 'year').format('YYYY')
                        }
                      });
                    }
                  }>{moment().subtract(2, 'year').format('YYYY')}年</Button>
                  <Divider type="vertical"/>
                  <Button type="link" onClick={
                    () => {
                      dispatch({
                        type: 'dashboardWorkplace/fetchQueryYearExportvolumeData',
                        payload: {
                          date: moment().subtract(1, 'year').format('YYYY')
                        }
                      });
                    }
                  }>{moment().subtract(1, 'year').format('YYYY')}年</Button>
                  <Divider type="vertical"/>
                  <Button type="link" onClick={
                    () => {
                      dispatch({
                        type: 'dashboardWorkplace/fetchQueryYearExportvolumeData',
                        payload: {
                          date: moment().format('YYYY')
                        }
                      });
                    }
                  }>{moment().format('YYYY')}年</Button>
                </span>
              }
              loading={fetchAmtdetailDataLoading}
              bodyStyle={{padding: 0}}
            >
              <ExportVolumeChart/>
            </Card>

            <Card
              className={styles.projectList}
              style={{marginBottom: 24}}
              headStyle={{border: 0}}
              title="外汇金额统计"
              bordered={false}
              extra={
                <span>
                  <Button type="link" onClick={
                    () => {
                      dispatch({
                        type: 'dashboardWorkplace/fetchQueryYearRecamountData',
                        payload: {
                          date: moment().subtract(2, 'year').format('YYYY')
                        }
                      });
                    }
                  }>{moment().subtract(2, 'year').format('YYYY')}年</Button>
                  <Divider type="vertical"/>
                  <Button type="link" onClick={
                    () => {
                      dispatch({
                        type: 'dashboardWorkplace/fetchQueryYearRecamountData',
                        payload: {
                          date: moment().subtract(1, 'year').format('YYYY')
                        }
                      });
                    }
                  }>{moment().subtract(1, 'year').format('YYYY')}年</Button>
                  <Divider type="vertical"/>
                  <Button type="link" onClick={
                    () => {
                      dispatch({
                        type: 'dashboardWorkplace/fetchQueryYearRecamountData',
                        payload: {
                          date: moment().format('YYYY')
                        }
                      });
                    }
                  }>{moment().format('YYYY')}年</Button>
                </span>
              }
              loading={fetchAmtdetailDataLoading}
              bodyStyle={{padding: 0}}
            >
              <ForeignExchangeAmountChart/>
            </Card>
            <Card
              className={styles.projectList}
              headStyle={{border: 0}}
              style={{marginBottom: 24}}
              title="订单数量统计"
              bordered={false}
              extra={
                <span>
                  <Button type="link" onClick={
                    () => {
                      dispatch({
                        type: 'dashboardWorkplace/fetchOrderYearNumData',
                        payload: {
                          date: moment().subtract(2, 'year').format('YYYY')
                        }
                      });
                    }
                  }>{moment().subtract(2, 'year').format('YYYY')}年</Button>
                  <Divider type="vertical"/>
                  <Button type="link" onClick={
                    () => {
                      dispatch({
                        type: 'dashboardWorkplace/fetchOrderYearNumData',
                        payload: {
                          date: moment().subtract(1, 'year').format('YYYY')
                        }
                      });
                    }
                  }>{moment().subtract(1, 'year').format('YYYY')}年</Button>
                  <Divider type="vertical"/>
                  <Button type="link" onClick={
                    () => {
                      dispatch({
                        type: 'dashboardWorkplace/fetchOrderYearNumData',
                        payload: {
                          date: moment().format('YYYY')
                        }
                      });
                    }
                  }>{moment().format('YYYY')}年</Button>
                </span>
              }
              loading={fetchAmtdetailDataLoading}
              bodyStyle={{padding: 0}}
            >
              <OrderCountChart/>
            </Card>
          </Col>
          <Col xl={8} lg={24} md={24} sm={24} xs={24}>
            <Card
              style={{marginBottom: 24}}
              title="快捷方式"
              bordered={false}
              bodyStyle={{padding: 0}}
            >
              <EditableLinkGroup onAdd={() => {
              }} links={links} linkElement={Link}/>
            </Card>
          </Col>
        </Row>

        <Modal
          destroyOnClose
          title="提现"
          visible={this.state.cashVisible}
          width={600}
          onCancel={() => this.setState({cashVisible: false})}
          onOk={() => {
            this.props.form.validateFields((err, values) => {
              if (err) return message.err("填写的参数不完整");
              axios.ajax({url: `${MC_PATH}/api/presentrecord`, params: values}, 'post').then(res => {
                if (res.resultCode == 'ok') {
                  this.setState({cashVisible: false});
                  message.info('提现申请已成功发送!');
                  return;
                }
                message.error(res.errMessage)
              })
            })
          }}
        >
          <Form layout='inline'>
            <FormItem label="金额" colon={false}>
              {getFieldDecorator('amt', {
                initialValue: '',
                rules: [
                  {required: true, message: '提现金额不能为空'},
                  {
                    pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                    message: '请正确填写金额',
                  },
                ],
              })(<InputNumber min={0} style={{width: 200}} placeholder='请输入提现金额'/>)}
            </FormItem>
          </Form>
        </Modal>


        <Modal
          destroyOnClose
          title="提现记录查询"
          visible={this.state.cashRecordVisible}
          width={600}
          footer={false}
          onCancel={() => this.setState({cashRecordVisible: false})}
        >

          <Table
            columns={this.columns}
            dataSource={this.state.CashRecordList || []}
            size="small"
            pagination={false}
          />

        </Modal>


      </PageHeaderWrapper>
    );
  }
}

export default Form.create()(Workplace);
